package leetcode.leetcode_102;


import java.util.*;


class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> nodes = new LinkedList<>();
        nodes.add(root);
        while (!nodes.isEmpty()) {
            int size = nodes.size();
            ArrayList<Integer> nodeValList = new ArrayList<>();
            while(size -- >0){
                TreeNode poll = nodes.poll();
                nodeValList.add(poll.val);
                if (poll.left != null) {
                    nodes.add(poll.left);
                }
                if (poll.right != null) {
                    nodes.add(poll.right);
                }
            }
            list.add(nodeValList);
        }
        return list;
    }
}